<template>
  <div class="player_box"
       v-show="playList.length"
       ref='player'>
    <transition name='normal'
                @enter='cd_enter'
                @after-enter="cd_after_enter"
                @leave='cd_leave'
                @after-leave="cd_after_leave">
      <div class="play_main"
           v-show="fullScreen"
           ref='play_main'>
        <div :style="{backgroundImage: `url(${currentSong && currentSong.image})`}"
             class="player_cover_url">
        </div>
        <div class="play_top"
             ref='play_top'>
          <div class="top">
            <div class="back"
                 @click='tosetPlay(false)'>
              <i class="icon-back"></i>
            </div>
            <div class="text-center text_ellipsis"
                 v-html="currentSong && currentSong.songname">
            </div>
            <div class="text-center singer text_ellipsis"
                 v-html="currentSong && currentSong.singer">
            </div>
          </div>
        </div>
        <div class="player-middle">
          <mt-swipe :prevent='false'
                    :stopPropagation='false'
                    :auto="slider_param.auto"
                    :showIndicators='slider_param.showIndicators'
                    class="player-slider-box"
                    @change="handleChange">
            <mt-swipe-item>
              <!-- 专辑图片 -->
              <div :class="['album_url',playing ? 'rotate':'pause']"
                   ref='cd'>
                <img :src="currentSong && currentSong.image"
                     alt="">
              </div>

              <div class='text-center one_words'>{{oneWords}}</div>
            </mt-swipe-item>
            <mt-swipe-item>
              <!-- 歌词 滚动 -->
              <Scroll class="middle-r"
                      ref="lyricScroll"
                      :data="currentLyric && currentLyric.lines">
                <div class="lyric-wrapper">
                  <div v-if="currentLyric">
                    <p ref="lyricLine"
                       class="text"
                       :class="{'current': lyricIndex === index}"
                       v-for="(line,index) in currentLyric.lines"
                       :key='index'>{{line.txt}}</p>
                  </div>
                  <p v-else
                     class="text">加载歌词中</p>
                </div>
              </Scroll>
            </mt-swipe-item>
          </mt-swipe>
          <div class="dots">
            <span class="dot"
                  :class="{active: i === index }"
                  v-for="(item, index) in dots"
                  :key='index'></span>
          </div>
        </div>
        <div class="player-bottom">
          <div class="middle_bottom">
            <div class="schedule_strip_box flex_space_between">
              <div class="left schedule_time">{{currentTime | format}}</div>
              <div class="center">
                <progress-bar :percent='percent'
                              @changeCurrentTime='changeCurrentTime'></progress-bar>
              </div>
              <div class="right schedule_time">{{currentSong.time | format}}</div>
            </div>
            <div class="flex_space_between operation_box">
              <div class="icon">
                <i :class='iconMode'
                   @click="changeMode"></i>
              </div>
              <div class="icon">
                <i class='icon-prev'
                   @click="toArrow('prev')"></i>
              </div>
              <div class="icon play_icon"
                   @click.stop="setPlaying">
                <i :class='playIcon'></i>
              </div>
              <div class="icon">
                <i class='icon-next'
                   @click="toArrow('next')"></i>
              </div>
              <div class="icon">
                <i class='icon-heart'></i>
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition>
    <transition name='mini'>
      <div class="play_mini flex_start"
           v-show="!fullScreen"
           @click="tosetPlay(true)">
        <img :class="['mini_url',playing ? 'rotate':'pause']"
             :src="currentSong && currentSong.image">
        <div class="song_info">
          <div class="song_name text_ellipsis">{{currentSong && currentSong.songname}}</div>
          <div class="song_singer">{{currentSong && currentSong.singer}}</div>
        </div>
        <div class='_control flex_start'>
          <div class="play_control"
               @click.stop="setPlaying">

            <progress-circle :width='24'
                             :percent='percent'>
              <i :class="miniIcon"></i>
            </progress-circle>
          </div>
          <div class="song_list_control">
            <i class="icon-playlist"></i>
          </div>
        </div>
      </div>
    </transition>
    <audio ref='audio'
           :src="currentSong.songUrl"
           @ended='end'
           @canplay='ready'
           @error='playError'
           @timeupdate='duration'></audio>
    <transition name='fade'>
      <div class="loading-container"
           v-show='loading'>
        <loading title='该资源暂时下架>_<'
                 @close='loading = false'></loading>
      </div>
    </transition>
  </div>
</template>

<script>
import * as types from 'store/modules/player/mutation_types'
import animations from 'create-keyframe-animation'
import { prefixStyle, format } from 'common/js/dom'
import loading from 'base/loading/loading'
import progressBar from 'base/progress/progress-bar'
import progressCircle from 'base/progress-circle/progress-circle'
import { playMode } from 'common/js/config'
import Lyric from 'lyric-parser'
import Scroll from 'base/scroll/scroll'
// 播放器模块
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapGetters, mapMutations, mapActions } = createNamespacedHelpers('player')
const transform = prefixStyle('transform')
const transitionend = prefixStyle('transitionend')
export default {
  data () {
    return {
      // swipe参数
      slider_param: {
        auto: 0,
        showIndicators: false
      },
      // 操作区图标
      // 加载标识
      songReady: false,
      loading: false,
      // 当前歌词
      playLyric: '',
      // 当前歌曲歌词数据
      currentLyric: null,
      // 第几行
      lyricIndex: 0,
      currentTime: 0,
      // 之前播放模式
      prevMode: 0,
      // 当前索引
      i: 0,
      dots: 2
    }
  },

  filters: {
    // 初始化时间
    format (num) {
      return format(num)
    }
  },
  methods: {
    // 切换
    handleChange (i) {
      this.i = i
    },
    // 获取歌词
    _getSonglyric (song) {
      song.getLyric().then((lyric) => {
        if (this.currentSong.lyric !== lyric) return false
        this.currentLyric = new Lyric(lyric, this.handleLyric)
        if (this.playing) this.currentLyric.play()
        console.log(this.currentLyric)
      }).catch(() => {
        this.clearLyric()
      })
    },
    clearLyric () {
      this.currentLyric = null
      this.playLyric = ''
      this.lyricIndex = 0
    },
    // 歌词处理
    handleLyric ({ lineNum, txt }) {
      this.lyricIndex = lineNum
      // 歌词聚焦到中间
      if (lineNum > 5) {
        // 上移
        let el = this.$refs.lyricLine[lineNum - 5]
        this.$refs.lyricScroll.scrollToElement(el, 1000)
      } else {
        this.$refs.lyricScroll.scrollTo(0, 0, 1000)
      }
      this.playLyric = txt
    },
    // 改变播放模式
    changeMode () {
      let mode = (this.mode + 1) % 3
      this.setMode(mode)
      console.log(mode)
    },
    // 拖动进度条
    changeCurrentTime (percent) {
      let newTime = this.currentSong.time * percent
      this.$refs.audio.currentTime = newTime
      // 同步歌词 毫秒为单位
      if (this.currentLyric) this.currentLyric.seek(newTime * 1000)
    },
    // 播放时间
    duration (e) {
      this.currentTime = this.$refs.audio.currentTime
    },
    ready () {
      this.songReady = true
    },
    playError () {
      console.log(123)
      this.songReady = true
      this.loading = true
      this.setPlaying()
      setTimeout(() => {
        this.loading = false
        this.toArrow('next')
      }, 1000)
    },
    end () {
      console.log('播放结束')
      // 单曲循环的处理
      if (this.mode === playMode.loop) {
        return this.loop()
      }
      this.toArrow('next')
    },
    loop () {
      if (this.currentLyric) this.clearLyric.seek(0)
      this.$refs.audio.play()
    },
    // 播放/暂停
    setPlaying () {
      console.log('播放/暂停')
      this._setPlaying(!this.playing)
      if (this.currentLyric) this.currentLyric.togglePlay()
    },
    // 上下首 控制播放列表
    async toArrow (arrow) {
      if (!this.songReady) return false
      // 播放列表只有一首歌
      if (this.playList.length === 1) return this.loop()
      // 播放模式 是否改变过
      if (this.prevMode !== this.mode) {
        if (this.mode === playMode.random) {
          await this.changePlayList(this._.shuffle(this.playList))
        } else {
          this.setCurrentIndex(this.currentSong.index)
          await this.changePlayList(this.sequenceList)
        }
        this.prevMode = this.mode
      }

      // 在模式的改变下修改当前播放列表
      if (arrow === 'prev') this.prev()
      if (arrow === 'next') this.next()
      this.songReady = false
    },
    // 切换播放器
    tosetPlay (flag) {
      this.setFull(flag)
    },

    // cd动画钩子
    cd_enter (el, done) {
      const { x, y, scale } = this._getCdMini()
      // 进入的时候
      let animation = {
        0: {
          transform: `translate3d(${x}px,${y}px,0) scale(${scale})`
        },
        60: {
          transform: `translate3d(0,0,0) scale(1.1)`
        },
        100: {
          transform: `translate3d(0,0,0) scale(1)`
        }
      }
      // 注册
      animations.registerAnimation({
        name: 'move',
        // 动画
        animation,
        // 动画属性
        presets: {
          duration: 400,
          easing: 'linear'
        }
      })
      // 单个 执行动画
      animations.runAnimation(this.$refs.cd, 'move', done)
      // 多个
      // animations.runAnimation(this.$refs.cd, 'move').then(function () {
      //   // 还可以继续
      //   done()
      //   console.log(123)
      // })
    },
    cd_after_enter () {
      // 移除注册 重置属性
      animations.unregisterAnimation('move')
      this.$refs.cd.style.animation = ''
    },
    cd_leave (el, done) {
      const { x, y, scale } = this._getCdMini()
      this.$refs.cd.style.transition = `all 0.4s`
      this.$refs.cd.style[transform] = `translate3d(${x}px,${y}px,0) scale(${scale})`
      console.log(transitionend)
      // this.$refs.cd.addEventListener(transitionend, done)
      setTimeout(() => {
        done()
      }, 400)
    },
    cd_after_leave () {
      this.$refs.cd.style.transition = ``
      this.$refs.cd.style[transform] = ``
      this.$refs.play_main.style.display = 'none'
    },
    // 获得mini cd 之间的 差值
    _getCdMini () {
      var miniLeft = 10
      var paddingtop = 110
      var width = 300
      var targetWidth = 45
      var x = miniLeft - window.innerWidth * 0.1
      var scale = targetWidth / width
      var y = window.innerHeight - paddingtop - targetWidth - miniLeft
      return { x, y, scale }
    },
    ...mapMutations({
      setFull: types.SET_FULLSCREEN,
      _setPlaying: types.SET_PLAYING,
      prev: types.PREV_ONE,
      next: types.NEXT_ONE,
      setMode: types.SET_MODE,
      setCurrentIndex: types.SET_CURRENTINDEX
    }),
    ...mapActions([
      'changePlayList'
    ])

  },
  computed: {
    iconMode () {
      // 三个判断
      return this.mode === playMode.sequence ? 'icon-sequence' : this.mode === playMode.loop ? 'icon-loop' : 'icon-random'
    },
    // 播放进度百分比
    percent () {
      return this.currentTime / this.currentSong.time
    },
    // 当前唱的歌词
    oneWords () {
      return this.playLyric
    },
    playIcon () {
      return this.playing ? 'icon-pause' : 'icon-play'
    },
    miniIcon () {
      return this.playing ? 'icon-pause-mini' : 'icon-play-mini'
    },
    ...mapState([
      'currentIndex',
      'playList',
      'sequenceList',
      'fullScreen',
      'playing',
      'mode'
    ]),
    ...mapGetters([
      'currentList',
      'currentSong'
    ])
  },
  watch: {
    currentSong (news, old) {
      if (news) {
        console.log(news)
        // 还没加载
        this.$nextTick(() => {
          // 获取歌词
          if (this.currentLyric) {
            this.currentLyric.stop()
            this.clearLyric()
          }
          this._getSonglyric(news)
          this.$refs.audio.play()
        })
      }
    },
    playing (news) {
      this.$nextTick(() => {
        news ? this.$refs.audio.play() : this.$refs.audio.pause()
      })
    }
  },
  components: {
    loading,
    progressBar,
    progressCircle,
    Scroll
  },
  updated () {
    // console.log(this.currentSong)
  },
  created () {
    this.prevMode = this.mode
  }

}
</script>

<style scoped lang='stylus'  rel='stylesheet/stylus'>
@import '~common/stylus/variable'
@import '~common/stylus/mixin'
.normal-enter-active, .normal-leave-active
  transition all 0.4s
  .play_top, .player-bottom
    transition all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32)
.normal-enter, .normal-leave-to
  opacity 0
  .play_top
    transform translateY(-100px)
  .player-bottom
    transform translateY(100px)
.mini-enter-active, .mini-leave-active
  transition all 0.4s
.mini-enter, .mini-leave-to
  opacity 0
.icon
  color $color-theme
// 转动
.mini_url, .album_url
  animation rotate 15s linear infinite
.rotate
  animation-play-state running
.pause
  animation-play-state paused
@keyframes rotate
  0%
    transform rotate(0)
  100%
    transform rotate(360deg)
.middle-r
  display inline-block
  vertical-align top
  width 100%
  height 100%
  overflow hidden
  .lyric-wrapper
    width 80%
    margin 0 auto
    overflow hidden
    text-align center
    .text
      line-height 32px
      color $color-text-l
      font-size $font-size-medium
      &.current
        color $color-text
.player_box
  .play_mini
    position fixed
    left 0
    right 0
    bottom 0
    height 60px
    z-index 3
    background $color-background
  .play_main
    position fixed
    top 0
    left 0
    right 0
    bottom 0
    z-index 3
    background $color-background
    .player-middle
      position absolute
      top 80px
      bottom 170px
      left 0
      right 0
      .dots
        position absolute
        right 0
        left 0
        bottom -12px
        text-align center
        font-size 0
        .dot
          display inline-block
          margin 0 4px
          width 8px
          height 8px
          border-radius 50%
          background $color-text-l
          &.active
            width 20px
            border-radius 5px
            background $color-text-ll
    .player_cover_url
      position absolute
      top 0
      right 0
      bottom 0
      left 0
      background-size auto 100%
      background-position center
      filter blur(20px)
      opacity 0.5
      transform scale(1.1)
    .player-bottom
      position absolute
      bottom 50px
      // height 120px
      width 100%
  .play_top
    position relative
    height 80px
    .top
      overflow hidden
      position absolute
      top 0
      width 100%
      line-height 40px
      color #fff
      font-size $font-size-medium-x
      z-index 4
      .singer
        font-size $font-size-medium
      div.text-center
        margin 0 48px
      .back
        position absolute
        top 0
        left 6px
        z-index 50
        .icon-back
          display block
          padding 10px
          font-size $font-size-large-x
          color $color-theme
          transform rotate(-90deg)
  .player-middle
    .album_url
      width 80%
      margin 20px auto 30px
      border 10px solid rgba(255, 255, 255, 0.1)
      border-radius 50%
      overflow hidden
      img
        width 100%
        height 100%
    .one_words
      // margin-top 30px
      font-size $font-size-medium
      color $color-text-l
  .middle_bottom
    width 80%
    margin 0 auto
    .schedule_strip_box
      margin-bottom 15px
      flex-center()
      .center
        flex 1
      .schedule_time
        font-size $font-size-small
        flex 0 0 10%
        &.left
          margin-right 6px
        &.right
          margin-left 6px
          text-align right
    .operation_box
      font-size 26px
      flex-center()
      .play_icon
        font-size 32px
  .play_mini
    flex-center()
    .mini_url
      width 45px
      height 45px
      border-radius 50%
      margin-left 10px
      margin-right 10px
    .song_info
      flex 1
      overflow hidden
      font-size 14px
      .song_name
        margin-bottom 10px
        overflow hidden
        text-wrap none
    ._control
      &>div
        flex 0 0 30px
        width 30px
        &.play_control
          margin-left 5px
      color $color-theme
    .play_control
      position relative
      font-size 24px
      margin-right 10px
      i
        position relative
        z-index 0
        opacity 0.5
    .song_list_control
      font-size 24px
      margin-right 5px
      opacity 0.5
</style>